extends CharacterBody2D
const SPEED = 80.0

@onready var player_animated: AnimatedSprite2D = $PlayerAnimated
@onready var shade_handle_body: CollisionShape2D = $ShadeHandle/ShadeHandleBody
@onready var tree_tile_map: TileMapLayer = %tree
@onready var player: CharacterBody2D = %player
var area:Area2D

func _ready() -> void:
	if player :
		area = player.get_node("ShadeHandle")
		area.body_shape_entered.connect(area_body_shape_entered)
		area.body_shape_exited.connect(area_body_shape_exited)
	
func area_body_shape_entered(body_rid:RID,body:Node2D,body_shape_index:float,local_shape_index:float)->void:
	print("执行碰撞体进入透明度")
	set_tile_set_resource_shader_material(body_rid,body,body_shape_index,local_shape_index,.5)
	
func area_body_shape_exited(body_rid:RID,body:Node2D,body_shape_index:float,local_shape_index:float)->void:
	print("执行碰撞体退出透明度")
	set_tile_set_resource_shader_material(body_rid,body,body_shape_index,local_shape_index,0)

func set_tile_set_resource_shader_material(body_rid:RID,body:Node2D,body_shape_index:float,local_shape_index:float,shape:float)->void:
	var cell_coords = tree_tile_map.get_coords_for_body_rid(body_rid)
	var atlas_coords = tree_tile_map.get_cell_atlas_coords(cell_coords)
	var tile_set_atlas_source = tree_tile_map.tile_set.get_source(2) as TileSetAtlasSource
	var size = tile_set_atlas_source.get_tile_size_in_atlas(atlas_coords)
	var material = tree_tile_map.get_cell_tile_data(cell_coords).material
	if material != null:
		var shader = material as ShaderMaterial
		set_shader(shader,size.y*16,size.x*16,tree_tile_map.map_to_local(cell_coords),shape)

func set_shader(shader:ShaderMaterial,height:float,width:float,cell_pos:Vector2,shape:float)->void:
	shader.set_shader_parameter("cell_pos",cell_pos)
	shader.set_shader_parameter("width",width)
	shader.set_shader_parameter("height",height)
	shader.set_shader_parameter("shape",shape)

func _physics_process(delta: float) -> void:
	# Get the input direction and handle the movement/deceleration.
	# As good practice, you should replace UI actions with custom gameplay actions.
	var direction := Input.get_vector("walk_left", "walk_right","walk_top","walk_down").normalized()
	if direction:
		velocity = direction * SPEED
	else:
		velocity = Vector2.ZERO
	play_animation(direction)
	#这个方法会被牛牛推走
	#move_and_slide()
	#使用此方法可以止牛把人推走
	move_and_collide(velocity * delta)
	
func play_animation(dir:Vector2)->void:
	if player_animated and dir:
		if dir.x > 0:
			player_animated.play("walk_right")
		elif dir.x < 0:
			player_animated.play("walk_left")
		elif dir.y < 0:
			player_animated.play("walk_up")
		elif dir.y > 0:
			player_animated.play("walk_down")
		else:
			player_animated.stop()
